package com.sec.android.app.myfiles.receiver;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.local.file.LocalFileDbTableInfo;
import com.sec.android.app.myfiles.module.local.recent.RecentDbTableInfo;
import com.sec.android.app.myfiles.module.shortcut.ShortcutFileRecord;
import com.sec.android.app.myfiles.module.shortcut.cmd.AddShortcutCmd;
import com.sec.android.app.myfiles.provider.DbTableInfo;
import com.sec.android.app.myfiles.provider.PrivateMyFilesProvider;
import com.sec.android.app.myfiles.util.StorageMonitor;
import com.sec.android.app.myfiles.util.UiUtils;

public final class MyFilesReceiver extends BroadcastReceiver {
    private static final String DATA = "_data";
    private static final String DOWNLOAD_BY = "_download_by";
    private static final String DESCRIPTION = "_description";
    private static final Uri MYFILE_CONTENT_URI = Uri.parse("content://myfiles/download_history");
    private static final String ACTION_MTP_FILE_SCAN = "com.samsung.intent.action.MTP_FILE_SCAN";
    private static final String ACTION_HOME_SHORTCUT_INFO = "com.sec.android.app.myfiles.HOME_SHORTCUT_INFO";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            String action = intent.getAction();
            Log.d(this, "onReceive() ] action : " + action);

            if (action == null) {
                return;
            }

            if (UiUtils.isFactoryMode(context)) {
                return;
            }

            switch (action) {
                case ACTION_MTP_FILE_SCAN:
                    String[] paths = intent.getStringArrayExtra("files");
                    if (paths != null) {
                        new InsertMtpFilesThread(context, paths).start();
                    }
                    break;
                case Intent.ACTION_MEDIA_EJECT:
                case Intent.ACTION_MEDIA_UNMOUNTED:
                    Uri uri = intent.getData();
                    if (uri != null) {
                        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
                            StorageMonitor.updateSubSystemStorageState(context);
                            String path = uri.getPath();
                            if (path != null && !AppFeatures.isBYOD() && !AppFeatures.isKnox()) {
                                OnMediaEjectOrUnmount(context, path);
                            }
                        }
                    }
                    break;
                case ACTION_HOME_SHORTCUT_INFO:
                    String path = intent.getStringExtra(AppConstants.INTENT_KEY_FILE_PATH);
                    FileRecord record = FileRecord.createFileRecord(FileRecord.StorageType.Local, path);
                    AddShortcutCmd.addShortcutToMyFilesDB(context, record, FileRecord.ShortcutType.HomeScreen);
                    break;
            }
        } else {
            Log.e(this, "onReceive - intent is null");
        }
    }

    private void OnMediaEjectOrUnmount(Context context, String path) {
        Log.i(this, "OnMediaEjectOrUnmount: " + path);

        deleteLocalFileProvider(context, path);
        deleteRecentFileProvider(context, path);
        clearCache(context);

        PrivateMyFilesProvider.refreshDb(context, new ShortcutFileRecord());
        PrivateMyFilesProvider.clearCache(context, FileRecord.createFileRecord(FileRecord.StorageType.Local, path));
    }

    private void clearCache(Context context) {
        PrivateMyFilesProvider.clearCache(context, null);
    }

    private void deleteLocalFileProvider(Context context, String path) {
        ContentResolver cr = context.getContentResolver();
        DbTableInfo tableInfo = LocalFileDbTableInfo.getInstance();
        Uri uri = Uri.parse(tableInfo.getUri());
        String where = tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH) + " like ? ";
        String args[] = {
                path + "%"
        };
        cr.delete(uri, where, args);
    }

    private void deleteRecentFileProvider(Context context, String path) {
        ContentResolver cr = context.getContentResolver();
        DbTableInfo tableInfo = RecentDbTableInfo.getInstance();
        Uri uri = Uri.parse(tableInfo.getUri());
        String where = tableInfo.getColumnName(DbTableInfo.COLUMN_ID.PATH) + " like ? ";
        String args[] = {
                path + "%"
        };
        cr.delete(uri, where, args);
    }

    private static class InsertMtpFilesThread extends Thread {
        private Context mContext;
        private String[] mPaths;

        public InsertMtpFilesThread(Context context, String[] paths) {
            mContext = context;
            mPaths = paths;
        }

        @Override
        public void run() {
            int start = 0;
            Log.e(this, "InsertMtpFilesThread run Paths.length :" + mPaths.length);

            for (int i = start; i < mPaths.length; i++) {
                if (mPaths[i] != null) {
                    Log.i(this, "Mtp's Paths is :" + mPaths[i]);
                    ContentValues values = new ContentValues(3);
                    values.put(DATA, mPaths[i]);
                    values.put(DOWNLOAD_BY, 6);
                    values.put(DESCRIPTION, "MTP");
                    try {
                        mContext.getContentResolver().insert(MYFILE_CONTENT_URI, values);
                    } catch (Exception e) {
                        Log.e(this, "Adding mtp files failed");
                    }
                }
            }

        }
    }
}
